<template>
  <view class="map">
      <map scale="15" :show-location="true" id="map1756532712" :style="{height: (windowHeight / 1.5) + 'px'}" style="width: 100%; " :latitude="latitude" :polyline="polyline" :longitude="longitude" :markers="markers"></map>
      <!-- <canvas type="2d" style="width: 100%; height: 70vh;" id="map1756532712" canvas-id="map1756532712"
      class="map-canvas"></canvas> -->
      <!-- <view id="map1756532712" class="map-canvas" style="width: 100%; height: 70vh;"></view> -->
  </view>

</template>

<script>
import { drivingRoute } from '@/api/neighbor.js'
export default {
  props: {
    orderForm: {
      type: Object,
      default: () => { }
    }
  },

  data() {
    return {
      multiPolyline: {},
      pickup_address_marker: {},
      purchase_shop_marker: {},
      pickupLatLng: {},
      deliveryLatLng: {},
      delivery_address_marker: {},
      latitude: 32.016627,
      longitude: 120.269009,
      // latitude: 39.9042,
      // longitude: 116.4074,
      markers: [],
      mapContext: null,
      address: '',
      routeQuery: {},
      mapCtx: null,
      map: null, // 地图实例
      polyline: [], // 路线覆盖物
      origin: "39.9042,116.4074", // 起点坐标（示例：天安门）
      destination: "39.9163,116.3908", // 终点坐标（示例：故宫）
      routeInfo: null, // 路线信息
      amapKey: "1d9c46a1b58584cbfe469215ada5338c",
      windowHeight: 0
    }
  },
  onLoad(options) {
    if (options) this.routeQuery = options
  },
  mounted() {
    this.mapCtx = uni.createMapContext('map1756532712')
    let res = uni.getWindowInfo();
    this.windowHeight = res.windowHeight
    //     wx.chooseLocation({
    //    latitude: this.latitude,
    //    longitude: this.longitude,
    //    scale: 18
    //  })

  },
  methods: {
    _initMap() {
      let { is_report_location, service_status, purchase_address_type, _d, _p, _pur, type } = this.orderForm
      let polyline = [], markers = [], polyline_c = [], polyline_p = [], polyline_d = [], polyline_pur = []
      let p_marker = {}, pur_marker = {}, d_marker = {}
      let _c = { latitude: this.latitude, longitude: this.longitude }
      polyline_c.push({
        points: [_c, _c],
        color: '#FD6317',
        width: 5,
        arrowLine: true,
      })

      if (_p.lat && _p.lng) {
        polyline_p.push({
          points: [_c, { latitude: _p.lat, longitude: _p.lng }],
          color: '#FD6317',
          width: 6,
          arrowLine: true,
        })
        p_marker = {
          id: 1,
          latitude: Number(_p['lat']),
          longitude: Number(_p['lng']),
          width: 20,
          height: 34,
          title: '取件',
          iconPath: 'https://linshitong.oss-cn-shenzhen.aliyuncs.com/dev/image/2025/0903/dcf76202509030901021606.png'
        }
      }
      if (_d.lat && _d.lng) {
        if (type == 1 || type == 2) {
          polyline_d.push({
            points: [{ latitude: _p.lat, longitude: _p.lng }, { latitude: _d.lat, longitude: _d.lng }],
            color: '#00962B',
            width: 6,
            arrowLine: true,
          })
        } else {
          if (purchase_address_type == 1) {
            polyline_d.push({
              points: [{ latitude: _pur.lat, longitude: _pur.lng }, { latitude: _d.lat, longitude: _d.lng }],
              color: '#00962B',
              width: 6,
              arrowLine: true,
            })
          } else {
            polyline_d.push({
              points: [_c, { latitude: _d.lat, longitude: _d.lng }],
              color: '#00962B',
              width: 6,
              arrowLine: true,
            })
          }
        }
        d_marker = {
          id: 2,
          latitude: Number(_d.lat),
          longitude: Number(_d.lng),
          iconPath: 'https://linshitong.oss-cn-shenzhen.aliyuncs.com/dev/image/2025/0903/1f1d0202509030900287810.png',
          width: 20,
          height: 34,
          title: '收件'
        }
      }
      if (_pur.lat && _pur.lng) {
        polyline_pur.push({
          points: [_c, { latitude: _pur.lat, longitude: _pur.lng }],
          color: '#FD6317',
          width: 6,
          arrowLine: true,
        })
        pur_marker = {
          id: 4,
          latitude: Number(_pur.lat),
          longitude: Number(_pur.lng),
          width: 20,
          height: 34,
          title: '取件',
          iconPath: 'https://linshitong.oss-cn-shenzhen.aliyuncs.com/dev/image/2025/0903/dcf76202509030901021606.png'
        }
      }

      if (service_status == 1) {
        if (type == 1 || type == 2) {
          markers.push(p_marker, d_marker)
          polyline = polyline_c.concat(polyline_p).concat(polyline_d)
        }
        if (type == 3) {
          if (purchase_address_type == 1) {
            markers.push(pur_marker, d_marker)
            polyline = polyline_c.concat(polyline_pur).concat(polyline_d)
          } else {
            markers.push(d_marker)
            polyline = polyline_c.concat(polyline_d)
          }
        }
        if (type == 4 || type == 5) {
          markers.push(d_marker)
          polyline = polyline_c.concat(polyline_d)
        }
      } else if (service_status == 3) {
        markers.push(d_marker)
        polyline = polyline_c.concat(polyline_d)
      } else {
        if (type == 1 || type == 2) {
          markers.push(p_marker)
          polyline = polyline_c.concat(polyline_p)
        }
        if (type == 3) {
          if (purchase_address_type == 1) {
            markers.push(pur_marker)
            polyline = polyline_c.concat(polyline_pur)
          } else {
            markers.push(d_marker)
            polyline = polyline_c.concat(polyline_d)
          }
        }
        if (type == 4 || type == 5) {
          markers.push(d_marker)
          polyline = polyline_c.concat(polyline_d)
        }
      }

      this.markers = markers
      this.polyline = polyline
    },
    addRideMarker(_t) {
      if (_t && _t.lat && _t.lng) {
        this.latitude = Number(_t.lat)
        this.longitude = Number(_t.lng)
        let markers = JSON.parse(JSON.stringify(this.markers))
        markers.push({
          id: 3,
          latitude: this.latitude,
          longitude: this.longitude,
          width: 40,
        })
        this.markers = markers
      }

    },
    _drivingRoute() {
      let pl = [];
      let { is_report_location, service_status, neighbor_worker } = this.orderForm
      let polyline = []
      if (service_status == 1) {
        pl.push({ latitude: this.latitude, longitude: this.longitude })
        polyline.push({
          points: [{ latitude: this.latitude, longitude: this.longitude }],
          color: '#FD6317',
          width: 5,
          arrowLine: true,
        })


        if (this.orderForm.type == 1 || this.orderForm.type == 2) {
          if (this.pickupLatLng.latitude && this.pickupLatLng.longitude) {
            pl.push(JSON.parse(JSON.stringify(this.pickupLatLng)))
            polyline.push({
              points: [{ latitude: this.latitude, longitude: this.longitude }, JSON.parse(JSON.stringify(this.pickupLatLng))],
              color: '#FD6317',
              width: 6,
              arrowLine: true,
            })

          }

        }
        if (this.orderForm.type == 3) {
          if (this.orderForm.purchase_address_type == 1) {

            polyline.push({
              points: [{ latitude: this.latitude, longitude: this.longitude }, { latitude: this.orderForm.purchase_shop_lat, longitude: this.orderForm.purchase_shop_lng }],
              color: '#FD6317',
              width: 6,
              arrowLine: true,
            })
          }
        }
        if (this.deliveryLatLng.latitude && this.deliveryLatLng.longitude) {
          pl.push(JSON.parse(JSON.stringify(this.deliveryLatLng)))
          polyline.push({
            points: this.orderForm.type == 3 && this.orderForm.purchase_address_type == 1 ? [{ latitude: this.orderForm.purchase_shop_lat, longitude: this.orderForm.purchase_shop_lng }, JSON.parse(JSON.stringify(this.deliveryLatLng))] : [JSON.parse(JSON.stringify(this.pickupLatLng)), JSON.parse(JSON.stringify(this.deliveryLatLng))],
            color: '#00962B',
            width: 5,
            arrowLine: true,
          })

        }
      }
      if (service_status == 2) {
        pl.push({ latitude: this.latitude, longitude: this.longitude })
        if (this.orderForm.type != 3 && this.pickupLatLng.latitude && this.pickupLatLng.longitude) {
          pl.push(JSON.parse(JSON.stringify(this.pickupLatLng)))
        }
        if (this.orderForm.type == 3 && this.orderForm.purchase_shop_lng && this.orderForm.purchase_shop_lat) {
          pl.push(JSON.parse(JSON.stringify({ latitude: this.orderForm.purchase_shop_lat, longitude: this.orderForm.purchase_shop_lng })))
        }
        if (this.deliveryLatLng.latitude && this.deliveryLatLng.longitude) {
          pl.push(JSON.parse(JSON.stringify(this.deliveryLatLng)))
        }

      }
      if (service_status == 3) {
        pl.push({ latitude: this.latitude, longitude: this.longitude })
        if (this.deliveryLatLng.latitude && this.deliveryLatLng.longitude) {
          pl.push(JSON.parse(JSON.stringify(this.deliveryLatLng)))
        }
      }
      this.$nextTick(() => {
        if (pl.length) {
          let obj = {
            points: pl,
            color: service_status == 2 && (this.orderForm.type != 4 && this.orderForm.type != 5) ? '#FD6317' : '#00962B',
            width: 5,
            arrowLine: true,
            borderWidth: 0,
          }
          if (service_status == 1) {
            this.polyline = [obj]

          } else {
            this.polyline = [obj]

          }
          this.mapCtx.moveToLocation()

        }
      })

    },
    _drivingRoute1() {
      // this.mapCtx.moveToLocation({ latitude: this.orderForm.delivery_address_lat, longitude: this.orderForm.delivery_address_lng })
      drivingRoute().then(res => {
        if (res?.result?.result?.routes[0]?.polyline) {
          let coors = res.result.result.routes[0].polyline, pl = [];
          let kr = 1000000;
          let { is_report_location, service_status, neighbor_worker } = this.orderForm

          if (service_status == 1) {

          } else {
            if (is_report_location == 0) {

            }
          }

          if (this.pickupLatLng.latitude && this.pickupLatLng.longitude) {
            pl.push(this.pickupLatLng)
          }
          // for (var i = 2; i < coors.length; i++) {
          //   coors[i] = Number(coors[i - 2]) + Number(coors[i]) / kr;
          // }
          // for (var i = 0; i < coors.length; i += 2) {
          //   pl.push({ latitude: coors[i], longitude: coors[i + 1] })
          // }
          if (this.deliveryLatLng.latitude && this.deliveryLatLng.longitude) {
            pl.push(this.deliveryLatLng)
          }
          this.polyline = [{
            points: pl,
            color: '#00962B',
            width: 5,
            arrowLine: true,
            borderColor: '#0C7136',
            borderWidth: 1,
          }]
          this.mapCtx.moveToLocation(pl[0])

        }
      })
    },
    // 初始化地图
    initMap() {
      // 创建地图实例，传入你的高德地图Key
      this.map = new AMap.Map('map1756532712', {
        zoom: 11
      });
      this.$nextTick(() => {
        AMap.plugin('AMap.Geolocation', function () {
          var geolocation = new AMap.Geolocation({
            enableHighAccuracy: true, // 是否使用高精度定位，默认：true
            timeout: 10000, // 设置定位超时时间，默认：无穷大
            offset: [10, 20],  // 定位按钮的停靠位置的偏移量
            zoomToAccuracy: true,  //  定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
            position: 'RB' //  定位按钮的排放位置,  RB表示右下
          })

          geolocation.getCurrentPosition(function (status, result) {
            if (status == 'complete') {
              onComplete(result)
            } else {
              onError(result)
            }
          });

          function onComplete(data) {
            // data是具体的定位信息
          }

          function onError(data) {
            // 定位出错
          }
        })
        this.getRoute()
      })

      // 加载地图
    },

    // 获取骑行路线
    getRoute() {
      // 调用高德骑行路径规划API
      uni.request({
        url: "https://restapi.amap.com/v3/direction/bicycling",
        method: "GET",
        data: {
          origin: '32.455778, 119.923116',
          destination: '31.99, 120.28',
          key: '1d9c46a1b58584cbfe469215ada5338c',
          output: "json"
        },
        success: (res) => {
          const result = res.data;
          if (result.status === "1" && result.route?.paths?.length) {
            this.routeInfo = result.route.paths[0];
            this.drawRoute(result.route.paths[0]); // 绘制路线
          } else {
            uni.showToast({
              title: "路线规划失败: " + (result.info || "未知错误"),
              icon: "none"
            });
          }
        },
        fail: (err) => {
          uni.showToast({
            title: "请求失败，请检查网络",
            icon: "none"
          });
          console.error("路线请求失败:", err);
        }
      });
    },

    // 在地图上绘制路线
    drawRoute(path) {
      // 清除已有路线
      if (this.polyline) {
        this.map.remove(this.polyline);
      }

      // 解析路径坐标
      const pathPoints = path.steps.reduce((points, step) => {
        return points.concat(step.polyline.split(";").map(point => {
          const [lng, lat] = point.split(",");
          return [Number(lng), Number(lat)];
        }));
      }, []);

      // 创建路线覆盖物
      this.polyline = new AMap.Polyline({
        path: pathPoints,
        strokeColor: "#36BFFA", // 路线颜色
        strokeWeight: 6, // 路线宽度
        strokeOpacity: 0.8 // 路线透明度
      });

      // 添加路线到地图并调整视野
      this.map.add(this.polyline);
      this.map.setFitView([this.polyline], false, [50, 50, 50, 50]);

      // 添加起点终点标记
      this.addMarker(this.origin, "起点", "#4CAF50");
      this.addMarker(this.destination, "终点", "#F44336");
    },

    // 添加标记点
    addMarker(position, label, color) {
      const [lat, lng] = position.split(",").map(Number);
      new AMap.Marker({
        position: [lng, lat], // 注意高德坐标是[经度,纬度]
        map: this.map,
        label: {
          content: label,
          direction: "top"
        },
        icon: new AMap.Icon({
          size: new AMap.Size(30, 30),
          image: `https://a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png`,
          imageSize: new AMap.Size(30, 30)
        }),
        anchor: "bottom-center"
      });
    },
    buttonDriving(e) {
      var _this = this
      //通过wx.request发起HTTPS接口请求
      try {
        wx.request({
          //地图WebserviceAPI驾车路线规划接口 请求路径及参数（具体使用方法请参考开发文档）
          url: 'https://apis.map.qq.com/ws/direction/v1/driving/?key=1d9c46a1b58584cbfe469215ada5338c&from=39.894772,116.321668&to=39.902781,116.427171',
          success(res) {
            // var result = res.data.result
            // var route = result.routes[0]

            // var coors = route.polyline, pl = [];
            //   //坐标解压（返回的点串坐标，通过前向差分进行压缩）
            //   var kr = 1000000;
            //   for (var i = 2; i < coors.length; i++) {
            //     coors[i] = Number(coors[i - 2]) + Number(coors[i]) / kr;
            //   }
            //   //将解压后的坐标放入点串数组pl中
            //   for (var i = 0; i < coors.length; i += 2) {
            //     pl.push({ latitude: coors[i], longitude: coors[i + 1] })
            //   }
            //   _this.setData({
            //     // 将路线的起点设置为地图中心点
            //     latitude:pl[0].latitude,
            //     longitude:pl[0].longitude,
            //     // 绘制路线
            //     polyline: [{
            //       points: pl,
            //       color: '#58c16c',
            //       width: 6,
            //       borderColor: '#2f693c',
            //       borderWidth: 1
            //     }]
            //   })
          }
        })
      } catch (error) {

      }
    }
  }
}
</script>
